package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"io"
	"os"
	"path/filepath"
	"pets/cache"
	"pets/models"
	"time"
)

type PetsController struct {
	beego.Controller
}

func (c *PetsController) Add() {
	name := c.GetString("name")
	age, _ := c.GetInt("age")
	types := c.GetString("types")
	file, m, _ := c.GetFile("img")
	if m.Size >= 1024*1024*5 {
		c.Data["json"] = Res{
			Code:     500,
			Data:     nil,
			Database: "图片大小不能超过5mb",
		}
		c.ServeJSON()
		return
	}
	if filepath.Ext(m.Filename) != ".jpg" && filepath.Ext(m.Filename) != ".png" {
		c.Data["json"] = Res{
			Code:     500,
			Data:     nil,
			Database: "图片格式只能为jpg和png格式",
		}
		c.ServeJSON()
		return
	}
	openFile, _ := os.OpenFile("static/img/"+m.Filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
	io.Copy(openFile, file)
	pets := models.Pets{
		Name:  name,
		Age:   age,
		Types: types,
		Img:   "http://127.0.0.1:8080/static/img/" + m.Filename,
	}
	err := models.DB.Debug().Create(&pets).Error
	if err != nil {
		c.Data["json"] = Res{
			Code:     500,
			Data:     nil,
			Database: "发布失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code:     200,
			Data:     nil,
			Database: "发布成功",
		}
		c.ServeJSON()
		return
	}
}
func (c *PetsController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 2)
	size, _ := c.GetInt("size", 4)
	i := (page - 1) * size
	var pets []models.Pets
	var count int
	models.DB.Model(&models.Pets{}).Pluck("count(*)", &count)
	get, _ := cache.Rdb.Get(cache.Ctx, "pets_list").Result()
	if get != "" {
		json.Unmarshal([]byte(get), &pets)
	} else {
		models.DB.Debug().Offset(i).Limit(size).Find(&pets)
		mashal, _ := json.Marshal(&pets)
		cache.Rdb.Set(cache.Ctx, "pets_list", mashal, time.Minute*2)
	}
	c.Data["json"] = Res{
		Code: 200,
		Data: struct {
			T interface{}
			C int
		}{pets, count},
		Database: "展示成功",
	}
	c.ServeJSON()
	return
}
func (c *PetsController) Del() {
	id, _ := c.GetInt("id")
	var pets models.Pets
	models.DB.Debug().Where("id=?", id).Delete(&pets)
	c.Data["json"] = Res{
		Code:     200,
		Data:     nil,
		Database: "删除成功",
	}
	c.ServeJSON()
	return
}
func (c *PetsController) Show() {
	id, _ := c.GetInt("id")
	var pets models.Pets
	get, _ := cache.Rdb.Get(cache.Ctx, "pets_show").Result()
	if get != "" {
		json.Unmarshal([]byte(get), &pets)
	} else {
		models.DB.Debug().Where("id=?", id).First(&pets)
		mashal, _ := json.Marshal(&pets)
		cache.Rdb.Set(cache.Ctx, "pets_show", mashal, time.Minute*2)
	}
	c.Data["json"] = Res{
		Code:     200,
		Data:     pets,
		Database: "展示成功",
	}
	c.ServeJSON()
	return
}
